<?php
namespace app\api\controller\v1;
use think\Db;
use app\service\GaodeService;
use app\service\TravelService;
use app\service\TechnLastService;
use app\service\TechnService;
class Addorder extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}

    public function add(){
		$params = $this->data_post;
		$user = $this->user;
// 		exit;
// 		print_r($params);exit;

        // $params['service_arr']=[];
        // $params['service_arr'][0]['id']=3;
        // $params['service_arr'][0]['buy_number']=3;


		if(count($params['service_arr']) <= 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '请选择服务项目']);
            exit();
        }



		$order=db::name('order')->where('id',$params['order_id'])->find();


       


		//查询技师
		$techn = Db::name('techn')->where(['id' => $order['techn_id']])->find();
		if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}
		
		$longtime=0;
		
		if(($order['status']==6 && time()-$order['pre_end_time']<600)||$order['status']==2||$order['status']==3||$order['status']==4||$order['status']==5){
		    
		    
		    
    		$service_ids = trim($techn['service_ids'], ",");
    		$service_ids_arr = explode(",", $service_ids);
    		$service_list = [];    
    		    
    	    foreach($params['service_arr'] as $key => $value)
    		{
    			//选择项目匹配技师服务项目
    			if(in_array($value['id'], $service_ids_arr))
    			{
    				//查询服务项目
    				$service_info = Db::name('service')->where(['id' => $value['id'], 'is_shelves' => 1, 'is_delete_time' => 0])->find();
    				if(!empty($service_info))
    				{
    					//图片
    					if(!empty($params['open'])){
    					    $service_info['images'] = $service_info['images'];
    					}else{
    					    $service_info['images'] = request()->domain().$service_info['images'];
    					}
    					//价格美化
    					$service_info['price'] = PriceBeautify($service_info['price']);
    					
    					$service_info['original_price'] = PriceBeautify($service_info['original_price']);
    					//购买数量
    					$service_info['buy_number'] = $value['buy_number'];
    					//购买金额
    					$service_info['total_price'] = $value['buy_number']* ((float) $service_info['price']);
    					//技师昵称
    					$service_info['techn_nickname'] = $techn['nickname'];
    					
    					$service_list[] = $service_info;
    					
    					$longtime+=$service_info['duration']*$value['buy_number'];
    				}
    			}
    		}
    		
    		
    		// 订单总计基础信息组合
    		$total_price = empty($service_list) ? 0 : array_sum(array_column($service_list, 'total_price'));
    		    
    		    
    		    
    		
    		if(!empty($params['open'])){
    		    
    		    $jzorder['add_time']=time();
    		    $jzorder['order_id']=$order['id'];
    		    $jzorder['user_id']=$order['user_id'];
    		    $jzorder['price']=$total_price;
    		    $jzorder['techn_id']=$order['techn_id'];
    		    $jzorder['longtime']=$longtime;
    		    $jzorder['order_no']=date('YmdHis').GetRandomStr(6,'int');
    		    $jzorder['payment_id']=$params['payment_id'];
    		    
        		//处理服务预约开始时间date转时间戳
        		$pre_start_time = $order['pre_start_time'];
        		//处理服务预约结束时间(预约开始时间+服务时间分钟转为秒)
        		if($order['status']==5){
        		    $pre_end_time = $order['pre_end_time']+($longtime*60)+1800;
        		}else{
        		    $pre_end_time = time()+($longtime*60)+1800;
        		}
    		    
    		    $times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_start_time],'id'=>['<>',$order['id']]])->find();
		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可加钟']);
                	exit();
        		}
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_end_time],'pre_end_time'=>['>=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可加钟']);
                	exit();
        		}
        		
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可加钟']);
                	exit();
        		}
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['>=',$pre_start_time],'pre_end_time'=>['<=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可加钟']);
                	exit();
        		}

        		
        		
        		// 开始事务
        		Db::startTrans();
        		// 订单添加
        		$order_id = Db::name('order_jz')->insertGetId($jzorder);
        		if($order_id <= 0)
        		{
        			//事务回滚
        			Db::rollback();
        			echo json_encode(['code' => -1, 'msg' => '订单添加失败']);
                    exit();
        		}
        		//订单详情添加
        		$order_detail = [];
        		foreach($service_list as $key => $value)
        		{
        			$order_detail[$key]['jz_id'] = $order_id;
        			$order_detail[$key]['order_id'] = $order['id'];
        			$order_detail[$key]['service_id'] = $value['id'];
        			$order_detail[$key]['title'] = $value['title'];
        			$order_detail[$key]['images'] = $value['images'];
        			$order_detail[$key]['original_price'] = $value['original_price'];
        			$order_detail[$key]['price'] = $value['price'];
        			$order_detail[$key]['duration'] = $value['duration'];
        			$order_detail[$key]['buy_number'] = $value['buy_number'];
        			$order_detail[$key]['add_time'] = time();
        			$order_detail[$key]['upd_time'] = time();
        		}
        		$order_detail_count = Db::name('order_jzdetail')->insertAll($order_detail);
        		if($order_detail_count <= 0)
        		{
        			//事务回滚
        			Db::rollback();
        			echo json_encode(['code' => -1, 'msg' => '订单详情添加失败']);
                    exit();
        		}
        		
        		
        		// 提交事务
        		Db::commit();
        		$result['code'] = 0;
        		$result['msg'] = '下单成功';
        		$result['data'] = [
        			'order_id' => $order_id
        		];
        		echo json_encode($result);
                exit;
        
                
        		
    		}
    		
    		    
    		
    		    
    		// 数据返回组装
    		$result['code'] = 0;
    	    $result['msg'] = "请求成功";
    	    $result['data'] = [
    	    	'service_list' => $service_list,
    	    	'total_price' => $total_price,
    	    	'balance'=>$user['money'],
	    	    'gztext'=>file_get_contents(request()->domain().'/api/v1/webview/jyxy')
    	    ];
    		echo json_encode($result);
    		
		}else{
		    
		    echo json_encode(['code' => -100, 'msg' => '不可以加钟']);
			exit();
			
		}
		
		
    }
    
    
    
    // 补单
    public function budan_add(){
        
		$params = $this->data_post;
		$user = $this->user;
		
// 		$user=db::name('user')->where('id','1264')->find();
		
// 		$params['order_id']=1921;
		
// 		$params['pre_date']='2023-4-15 18:00';
		
// 		$params['open']=1;
		
// 		$params['address_id']=643;
// 		$params['payment_id']=3;
// 		$params['agreement']=true;
		
		$order=db::name('order')->where('id',$params['order_id'])->find();
		
		$order_detail=db::name('order_detail')->where('order_id',$params['order_id'])->select();
		
		$service_list=[];
		
		foreach ($order_detail as $k=>$v){
		    $v['images']=request()->domain().$v['images'];
			$v['total_price'] = $v['buy_number']* ((float) $v['price']);
			$service_list[]=$v;
		}
		
		
		//地址数据
		$address = null;
		$address_map = [
			'user_id' => $user['id'],
			'is_delete_time' => 0
		];
		//查询地址
		if(!empty($params['address_id']))
		{
			//如果地址id存在查询
			$address_map['id'] = $params['address_id'];
		}else
		{
			//查询用户默认地址
			$address_map['is_default'] = 1;
		}
		$address = Db::name('user_address')->where($address_map)->find();
		
		//查询技师
		$techn = Db::name('techn')->where(['id' => $order['techn_id']])->find();
		if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}
		
		
		
		//获取出行方式
		$travel_arr = TravelService::$travel_arr;
		$travel_id = 1;
		//出租车出行相关费用
		$taxi_travel = [];
		//距离
		$distance = 0;
		//费用
		$travel_price = 0;
		if(!empty($travel_arr[$travel_id]))
		{
			//查询技师实时数据
			$techn_last_info = Db::name('techn_last')->where(['techn_id' => $techn['id']])->find();
			//判断如果用户地址存在
			if(!empty($address) && !empty($techn_last_info))
			{
				$route_data = http_curl('https://restapi.amap.com/v3/direction/driving?origin='.$techn_last_info['lng'].','.$techn_last_info['lat'].'&destination='.$address['lng'].','.$address['lat'].'&extensions=base&output=JSON&key='.GaodeService::$web_api_key);
				$route_data = json_decode($route_data, true);
				if($route_data['status'] == 1 && $route_data['infocode'] == 10000)
				{
					$distance = PriceNumberFormat($route_data['route']['paths'][0]['distance']/1000); //行驶距离(米)
					//算费用
					//判断距离是否大于3公里
				// 	if($distance > $travel_arr[$travel_id]['config']['start_distance'])
				// 	{
				// 		//大于3公里
				// 		$surplus_dis = $distance-$travel_arr[$travel_id]['config']['start_distance'];
				// 		$travel_price = PriceNumberFormat((($surplus_dis*$travel_arr[$travel_id]['config']['distance_price'])+$travel_arr[$travel_id]['config']['start_price'])*2);
				// 	}else
				// 	{
				// 		//3公里内
				// 		$travel_price = $travel_arr[$travel_id]['config']['start_price']*2;
				// 	}
					
					$sys_chefei=db::name('chefei')->where(['proxy_id'=>0,'is_delete_time'=>0])->find();
					
					$proxy_id=db::name('proxy')->where('shi',$techn_last_info['city'])->value('proxy_id');
					
					if($proxy_id>0){
					    
					    $chefei=db::name('chefei')->where(['proxy_id'=>$proxy_id,'is_delete_time'=>0])->find();
					    
					    if(!empty($chefei)){
					        
					        $sys_chefei=$chefei;
					        
					    }
					    
					    
					}
					
					
					$h=date('H');
					
					
					$h1=!empty($sys_chefei['h1'])?$sys_chefei['h1']:'7';
					$h2=!empty($sys_chefei['h2'])?$sys_chefei['h2']:'21';
					
					$start_price=$sys_chefei['start_price_b'];//起步价
					$distance_price=$sys_chefei['distance_price_b'];//每公里单价
					
					if($h<$h1||$h>$h2){//晚间
					    $start_price=$sys_chefei['end_price_y'];
					    $distance_price=$sys_chefei['distance_price_y'];
					}
					
					if($distance > $sys_chefei['start_distance'])
					{
						//大于3公里
						$surplus_dis = $distance-$sys_chefei['start_distance'];
						$travel_price = PriceNumberFormat((($surplus_dis*$distance_price)+$start_price)*2);
					}else
					{
						//3公里内
						$travel_price = $start_price*2;
					}
					
					
					
				}
			}
			
		}
		
		
		if(!empty($params['open'])){
		    
		    $orinfo=db::name('order')->where(['status'=>9,'budan_id'=>['>',0],'user_id'=>$user['id']])->find();
		    if(!empty($orinfo)){
		        echo json_encode(['code' => -1, 'msg' => '请先处理已提交的补单信息']);
                exit();
		    }
		    
		    $validate = $this->validate(
    			$params,
    			[
    				'address_id' => 'require',
    				'pre_date' => 'require',
    				'payment_id' => 'require',
    				'agreement' => 'require|eq:false',
    			],
    			[
    				'address_id.require' => '请选择地址',
    				'pre_date.require' => '请选择预约时间',
    				'payment_id.require' => '请选择支付方式',
    				'agreement.require' => '请同意协议',
    				'agreement.eq' => '请同意协议',
    			]
    		);
    		if(true !== $validate)
            {
                echo json_encode(['code' => -1, 'msg' => $validate]);
                exit();
            }
            
            
            //地址数据
            $address = Db::name('user_address')->where(['id' => $params['address_id'], 'user_id' => $user['id'], 'is_delete_time' => 0])->find();
            if(empty($address))
            {
            	echo json_encode(['code' => -1, 'msg' => '地址不存在']);
                exit();
            }
            
        
            // 订单总价
    		$total_price = 0;
    		// 订单总计时长
    		$total_duration = $order['buy_number_duration'];
    		// 订单实际支付金额(已减去优惠金额, 已加上增加金额)
    		$actual_price = $travel_price;
    		// 订单优惠金额
    		$preferential_price = 0;
    		//扩展展示数据
    		$extension_data = [];
    		//获取出行方式
    		$travel_arr = TravelService::$travel_arr;
    		
    		$travel_id = 1;
    		//出租车出行相关费用
    		//距离
    		
            
            //处理服务预约开始时间date转时间戳
    		$pre_start_time = strtotime($params['pre_date']);
    		//处理服务预约结束时间(预约开始时间+服务时间分钟转为秒)
    		$pre_end_time = $pre_start_time+($total_duration*60);
    		
    		$pre_end_time2=$pre_end_time+1800;

    		//判断技师是否在接单状态
    		if($techn['work_status'] != 1)
    		{
    			echo json_encode(['code' => -1, 'msg' => '技师不在工作状态']);
                exit();
    		}
    		//判断预约时间是否大于当前时间
    		if((time()+900) >= $pre_start_time)
    		{
    			echo json_encode(['code' => -1, 'msg' => '超过预约时间']);
                exit();
    		}
    		
    		
    		
    		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_start_time]])->find();

    		if(!empty($times_order)){
    		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
    		}
    		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_end_time2],'pre_end_time'=>['>=',$pre_end_time2]])->find();

    		if(!empty($times_order)){
    		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
    		}

    		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_end_time2]])->find();

    		if(!empty($times_order)){
    		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
    		}
    		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['>=',$pre_start_time],'pre_end_time'=>['<=',$pre_end_time2]])->find();

    		if(!empty($times_order)){
    		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
    		}
    		
    		$reason=db::name('refund_log')->where(['uid'=>$user['id'],'day'=>date('Y-m-d')])->count('id');
    		
    		if($reason>2 && $user['id'] != 115){
    		    echo json_encode(['code' => -1, 'msg' => '今日退款达到三次,不可下单']);
            	exit();
    		}
    		
    		//技师预约时间节点
            $reservation_node = [];
            //查询技师已预约的订单
            $order_list = Db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
            if(!empty($order_list))
            {
            	foreach($order_list as $key => $value)
            	{
            		if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
            		{
            			//处理时间节点
            			/*if($value['service_time'] > 0)
            			{
            				$new_pre_start_time = $value['service_time'];
            			    $new_pre_end_time = $value['service_time']+($value['buy_number_duration']*60)+900;
            			}else
            			{*/
            				$new_pre_start_time = $value['pre_start_time'];
            			    $new_pre_end_time = $value['pre_end_time']+900;
            			/*}*/
            			for($j = $new_pre_start_time; $j <= $new_pre_end_time; $j += 1800)
            			{
            				$reservation_node[] = date('Y-m-d H:i:s', $j);
            			}
            		}
            	}
            }
            $techn['no_pre_hour_slot'] = !empty($techn['no_pre_hour_slot']) ? json_decode($techn['no_pre_hour_slot'], true) : [];
    
    		//判断是否在技师工作时间
    		//判断是否选择接单开始时间与结束时间
    		$work_start_hour = !empty($techn['work_start_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_start_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 00:00:00');
    
    		$work_end_hour = !empty($techn['work_end_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_end_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 23:30:00');
    		if($work_start_hour > $work_end_hour)
    		{
    			if(!(($pre_start_time >= $work_start_hour || $pre_start_time <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
    			{
    				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
                	exit();
    			}
    		}elseif ($work_start_hour < $work_end_hour) {
    			if(!($pre_start_time >= $work_start_hour && $pre_start_time <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
    			{
    				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
                	exit();
    			}
    		}else
    		{
    			if(!(!in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
    			{
    				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
                	exit();
    			}
    		}
    		//查询是否有机构信息
    		$proxy_info = Db::name('proxy')->where(['sheng' => $techn['province'], 'shi' => $techn['city'], 'is_delete_time' => 0,'type'=>2])->find();
    		// 订单主信息
    		$order = [
    			'order_no' => date('YmdHis').GetRandomStr(6,'int'),
    			'techn_id' => $techn['id'],
    			'user_id' => $user['id'],
    			'user_note' => isset($params['user_note']) ? str_replace(['"', "'"], '', strip_tags($params['user_note'])) : '',
    			'payment_id' => $params['payment_id'],
    			'extension_data' => empty($extension_data) ? '' : json_encode($extension_data, JSON_UNESCAPED_UNICODE),
    			'buy_number_duration' => $total_duration,
    			'pre_start_time' => $pre_start_time,
    			'pre_end_time' => $pre_end_time,
    			'travel_id' => $travel_id,
    			'distance' => $distance,
    			'preferential_price' => ($preferential_price <= 0) ? 0.00 : PriceNumberFormat($preferential_price),
    			'price' => ($total_price <= 0) ? 0.00 : PriceNumberFormat($total_price),
    			'travel_price' => ($travel_price <= 0) ? 0.00 : PriceNumberFormat($travel_price),
    			'total_price' => ($actual_price <= 0) ? 0.00 : PriceNumberFormat($actual_price),
    			//'total_price' => 0.01,
    			'client_type' => ApplicationClientType(),
    			'proxy_id' => !empty($proxy_info) ? $proxy_info['proxy_id'] : 0,
    			'sheng' => $techn['province'],
    			'shi' => $techn['city'],
    			'qu' => $techn['county'],
    			'add_time' => time(),
    			'upd_time' => time(),
    			'budan_id'=>$params['order_id']
    		];
    		// 开始事务
    		Db::startTrans();
    		// 订单添加
    		$order_id = Db::name('order')->insertGetId($order);
    		if($order_id <= 0)
    		{
    			//事务回滚
    			Db::rollback();
    			echo json_encode(['code' => -1, 'msg' => '订单添加失败']);
                exit();
    		}
    		//订单详情添加
    		$order_details = [];
    		foreach($order_detail as $key => $value)
    		{
    		    
    			$value['order_id'] = $order_id;
    			$value['add_time'] = time();
    			$value['upd_time'] = time();
    			unset($value['id']);
    			$order_details[]=$value;
    		}
    		$order_detail_count = Db::name('order_detail')->insertAll($order_details);
    		if($order_detail_count <= 0)
    		{
    			//事务回滚
    			Db::rollback();
    			echo json_encode(['code' => -1, 'msg' => '订单详情添加失败']);
                exit();
    		}
    		//订单地址添加
    		$order_address_id = Db::name('order_address')->insertGetId([
    			'order_id' => $order_id,
    			'address_id' => $address['id'],
    			'name' => $address['name'],
    			'mobile' => $address['mobile'],
    			'province' => $address['province'],
    			'city' => $address['city'],
    			'county' => $address['county'],
    			'province_name' => $address['province_name'],
    			'city_name' => $address['city_name'],
    			'county_name' => $address['county_name'],
    			'address' => $address['address'],
    			'address_des' => $address['address_des'],
    			'lng' => $address['lng'],
    			'lat' => $address['lat'],
    			'add_time' => time(),
    			'upd_time' => time()
    		]);
    		if($order_address_id <= 0)
    		{
    			//事务回滚
    			Db::rollback();
    			echo json_encode(['code' => -1, 'msg' => '订单地址添加失败']);
                exit();
    		}
    		
	        TechnService::TechnPreTimey($techn['id']);
    		// 提交事务
    		Db::commit();
    		$result['code'] = 0;
    		$result['msg'] = '下单成功';
    		$result['data'] = [
    			'order_id' => $order_id
    		];
    		echo json_encode($result);
    		//走队列
    		//创建任务： 项目命名空间\模块\文件夹\控制器@方法
    		$job = "app\service\QueuesService@order_close";
    		//延时时间
    		$delayed_second = 300;
    		$queues_data = ['id' => $order_id];
    		\think\Queue::later($delayed_second, $job, $queues_data, 'order_close');
    		
    		exit;
    		
        
		}
		
		
		
		$base = [
			// 总价
			'total_price' => $travel_price,
			
			// 默认地址
			'address' => $address,
			'techn_id'=>$order['techn_id']
		];
		
		
		
		// 数据返回组装
		$result['code'] = 0;
	    $result['msg'] = "请求成功";
	    $result['data'] = [
	    	'service_list' => $service_list,
	    	'base' => $base,
	    	'user' => [
	    		'money' => $user['money']
	    	],
	    	'gztext'=>file_get_contents(request()->domain().'/api/v1/webview/jyxy')
	    ];
		echo json_encode($result);
		
		
		
		
		
    }
    
    
    
    
    //升级项目
    public function upgrade(){
        
		$params = $this->data_post;
		$user = $this->user;
// 		exit;
// 		print_r($params);exit;
// 		$user=db::name('user')->where('id','1264')->find();
//         $params['order_id']=2114;
//         $params['service_arr']=[];
//         $params['service_arr'][0]['id']=5;
//         $params['service_arr'][0]['buy_number']=10;
//         $params['open']=1;
//         $params['payment_id']=3;
		if(count($params['service_arr']) <= 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '请选择服务项目']);
            exit();
        }
        
		$order=db::name('order')->where('id',$params['order_id'])->find();
		
		$order_detail=db::name('order_detail')->where(['order_id'=>$params['order_id'],'showtype'=>1])->select();
		
		$service_list_local=[];
		
		foreach ($order_detail as $k=>$v){
		    $v['images']=request()->domain().$v['images'];
			$v['total_price'] = $v['buy_number']* ((float) $v['price']);
			$service_list_local[]=$v;
		}
		
		$total_price_local = empty($service_list_local) ? 0 : array_sum(array_column($service_list_local, 'total_price'));
		
		
		//查询技师
		$techn = Db::name('techn')->where(['id' => $order['techn_id']])->find();
		if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}
		
		$longtime=0;
		
		    
		$service_ids = trim($techn['service_ids'], ",");
		$service_ids_arr = explode(",", $service_ids);
		$service_list = [];    
		    
	    foreach($params['service_arr'] as $key => $value)
		{
			//选择项目匹配技师服务项目
			if(in_array($value['id'], $service_ids_arr))
			{
				//查询服务项目
				$service_info = Db::name('service')->field('id,title,images,price,original_price,duration')->where(['id' => $value['id'], 'is_shelves' => 1, 'is_delete_time' => 0])->find();
				if(!empty($service_info))
				{
					//图片
					if(!empty($params['open'])){
					    $service_info['images'] = $service_info['images'];
					}else{
					    $service_info['images'] = request()->domain().$service_info['images'];
					}
					//价格美化
					$service_info['price'] = PriceBeautify($service_info['price']);
					
					$service_info['original_price'] = PriceBeautify($service_info['original_price']);
					//购买数量
					$service_info['buy_number'] = $value['buy_number'];
					//购买金额
					$service_info['total_price'] = $value['buy_number']* ((float) $service_info['price']);
					//技师昵称
					$service_info['techn_nickname'] = $techn['nickname'];
					
					$service_list[] = $service_info;
					
					$longtime+=$service_info['duration']*$value['buy_number'];
				}
			}
		}
		
		
		// 订单总计基础信息组合
		$total_price = empty($service_list) ? 0 : array_sum(array_column($service_list, 'total_price'));
		    
		$total_price=$total_price-$total_price_local;
		    
		
		if(!empty($params['open'])){
		    if($total_price<0){
    		    echo json_encode(['code' => -1, 'msg' => '服务金额过低']);
            	exit();
    		}
		    $jzorder['add_time']=time();
		    $jzorder['order_id']=$order['id'];
		    $jzorder['user_id']=$order['user_id'];
		    $jzorder['price']=$total_price;
		    $jzorder['techn_id']=$order['techn_id'];
		    $jzorder['longtime']=$longtime;
		    $jzorder['order_no']=date('YmdHis').GetRandomStr(6,'int');
		    $jzorder['payment_id']=$params['payment_id'];
		    
    		//处理服务预约开始时间date转时间戳
    		$pre_start_time = $order['pre_start_time'];
    		//处理服务预约结束时间(预约开始时间+服务时间分钟转为秒)
    		if($order['status']!=5){
    		    echo json_encode(['code' => -1, 'msg' => '此状态不可预约']);
            	exit();
    		}
    		if($order['buy_number_duration']<$longtime){
    		    
		        $pre_end_time = $pre_start_time+($longtime*60)+1800;
		        
    		    $times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_start_time],'id'=>['<>',$order['id']]])->find();
    	
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可升级']);
                	exit();
        		}
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_end_time],'pre_end_time'=>['>=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可升级']);
                	exit();
        		}
        		
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可升级']);
                	exit();
        		}
        		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['>=',$pre_start_time],'pre_end_time'=>['<=',$pre_end_time],'id'=>['<>',$order['id']]])->find();
        		
        		if(!empty($times_order)){
        		    echo json_encode(['code' => -1, 'msg' => '该时间已被预约,不可升级']);
                	exit();
        		}
    		}
    		
    		// 开始事务
    		Db::startTrans();
    		// 订单添加
    		$order_id = Db::name('order_upgrade')->insertGetId($jzorder);
    		if($order_id <= 0)
    		{
    			//事务回滚
    			Db::rollback();
    			echo json_encode(['code' => -1, 'msg' => '订单添加失败']);
                exit();
    		}
    		//订单详情添加
    		$order_detail = [];
    		foreach($service_list as $key => $value)
    		{
    			$order_detail[$key]['up_id'] = $order_id;
    			$order_detail[$key]['order_id'] = $order['id'];
    			$order_detail[$key]['service_id'] = $value['id'];
    			$order_detail[$key]['title'] = $value['title'];
    			$order_detail[$key]['images'] = $value['images'];
    			$order_detail[$key]['original_price'] = $value['original_price'];
    			$order_detail[$key]['price'] = $value['price'];
    			$order_detail[$key]['duration'] = $value['duration'];
    			$order_detail[$key]['buy_number'] = $value['buy_number'];
    			$order_detail[$key]['add_time'] = time();
    			$order_detail[$key]['upd_time'] = time();
    		}
    		$order_detail_count = Db::name('order_updetail')->insertAll($order_detail);
    		if($order_detail_count <= 0)
    		{
    			//事务回滚
    			Db::rollback();
    			echo json_encode(['code' => -1, 'msg' => '订单详情添加失败']);
                exit();
    		}
    		
    		
    		// 提交事务
    		Db::commit();
    		$result['code'] = 0;
    		$result['msg'] = '下单成功';
    		$result['data'] = [
    			'order_id' => $order_id
    		];
    		echo json_encode($result);
            exit;
    
            
    		
		}
		
		    
		
		    
		// 数据返回组装
		$result['code'] = 0;
	    $result['msg'] = "请求成功";
	    $result['data'] = [
	    	'service_list_local' => $service_list_local,
	    	'service_list' => $service_list,
	    	'total_price' => $total_price,
	    	'balance'=>$user['money'],
	    	'gztext'=>file_get_contents(request()->domain().'/api/v1/webview/jyxy')
	    ];
		echo json_encode($result);
    		
		
    }
    
}